import React, { useEffect, useState } from 'react';
import { Timeline, Card, Tag, Spin, Button, Descriptions, Progress, Tooltip } from 'antd';
import { 
    ClockCircleOutlined, 
    CheckCircleOutlined, 
    ExclamationCircleOutlined,
    UpOutlined,
    DownOutlined,
    BranchesOutlined,
    FileTextOutlined,
    BarChartOutlined,
    UserOutlined,
    CalendarOutlined
} from '@ant-design/icons';
import './ModelVersionTimeline.less';

interface VersionItem {
    id: string | number;
    version: string;
    date: string;
    type: string;
    changelog?: string;
    performance?: Record<string, any>;
    metrics?: string;
    is_current?: boolean;
    is_active?: boolean;
    framework?: string;
    model_type?: string;
    creator?: string;
    path?: string;
}

interface ModelInfo {
    id: string | number;
    name: string;
    current_version?: string;
    framework?: string;
    model_type?: string;
    description?: string;
    created_on?: string;
    updated_on?: string;
    creator?: string;
}

interface Statistics {
    total_versions: number;
    version_types: string[];
}

interface TimelineData {
    timeline: VersionItem[];
    model_info: ModelInfo;
    statistics: Statistics;
}

interface Props {
    data: TimelineData | null;
    loading?: boolean;
    width?: number;
    height?: number;
}

const ModelVersionTimeline: React.FC<Props> = ({ 
    data, 
    loading = false, 
    width = 800, 
    height = 500 
}) => {
    const [expandedItems, setExpandedItems] = useState<Set<string | number>>(new Set());
    const [showAllVersions, setShowAllVersions] = useState(false);

    const toggleExpanded = (id: string | number) => {
        const newExpanded = new Set(expandedItems);
        if (newExpanded.has(id)) {
            newExpanded.delete(id);
        } else {
            newExpanded.add(id);
        }
        setExpandedItems(newExpanded);
    };

    const getVersionTypeColor = (type: string) => {
        switch (type?.toLowerCase()) {
            case 'major': return '#f50';
            case 'minor': return '#2db7f5';
            case 'patch': return '#87d068';
            case 'current': return '#52c41a';
            case 'hotfix': return '#fa8c16';
            case 'release': return '#722ed1';
            default: return '#666';
        }
    };

    const getVersionTypeIcon = (type: string, isCurrent: boolean) => {
        if (isCurrent) return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
        
        switch (type?.toLowerCase()) {
            case 'major': return <ExclamationCircleOutlined style={{ color: '#f50' }} />;
            case 'minor': return <ClockCircleOutlined style={{ color: '#2db7f5' }} />;
            case 'patch': return <CheckCircleOutlined style={{ color: '#87d068' }} />;
            case 'hotfix': return <ExclamationCircleOutlined style={{ color: '#fa8c16' }} />;
            case 'release': return <BranchesOutlined style={{ color: '#722ed1' }} />;
            default: return <ClockCircleOutlined style={{ color: '#666' }} />;
        }
    };

    const formatDate = (dateString: string) => {
        try {
            return new Date(dateString).toLocaleString('zh-CN');
        } catch {
            return dateString;
        }
    };

    const renderPerformanceMetrics = (performance: Record<string, any>) => {
        if (!performance || Object.keys(performance).length === 0) {
            return <div style={{ color: '#999' }}>无性能数据</div>;
        }

        return (
            <div style={{ marginTop: '12px' }}>
                {Object.entries(performance).map(([key, value]) => (
                    <div key={key} style={{ marginBottom: '8px' }}>
                        <span style={{ fontWeight: 'bold', color: '#666' }}>{key}:</span>
                        <span style={{ marginLeft: '8px' }}>
                            {typeof value === 'number' ? (
                                <Progress 
                                    percent={Math.min(value * 100, 100)} 
                                    size="small" 
                                    status={value > 0.8 ? 'success' : value > 0.6 ? 'normal' : 'exception'}
                                    format={() => `${(value * 100).toFixed(1)}%`}
                                />
                            ) : (
                                String(value)
                            )}
                        </span>
                    </div>
                ))}
            </div>
        );
    };

    const visibleVersions = showAllVersions ? data?.timeline : data?.timeline?.slice(0, 5);

    if (loading) {
        return (
            <div className="version-timeline-loading">
                <Spin size="large" />
                <div style={{ marginTop: 16 }}>正在加载版本时间线...</div>
            </div>
        );
    }

    if (!data || !data.timeline || data.timeline.length === 0) {
        return (
            <div className="version-timeline-empty">
                <div className="empty-icon">⏰</div>
                <div className="empty-title">暂无版本历史</div>
                <div className="empty-description">该模型暂时没有版本历史记录</div>
            </div>
        );
    }

    return (
        <div className="version-timeline-wrapper" style={{ maxHeight: height, overflow: 'auto' }}>
            {/* 模型信息概览 */}
            {data.model_info && (
                <Card 
                    title={
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <FileTextOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                            模型基本信息
                        </div>
                    }
                    size="small" 
                    style={{ marginBottom: 16 }}
                >
                    <Descriptions size="small" column={2}>
                        <Descriptions.Item label="模型名称">
                            <span style={{ fontWeight: 'bold', color: '#1890ff' }}>
                                {data.model_info.name}
                            </span>
                        </Descriptions.Item>
                        <Descriptions.Item label="当前版本">
                            <Tag color="green">{data.model_info.current_version}</Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="框架">
                            <Tag color="blue">{data.model_info.framework}</Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="类型">
                            <Tag color="purple">{data.model_info.model_type}</Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="创建者">
                            <span>
                                <UserOutlined style={{ marginRight: 4 }} />
                                {data.model_info.creator}
                            </span>
                        </Descriptions.Item>
                        <Descriptions.Item label="创建时间">
                            <span>
                                <CalendarOutlined style={{ marginRight: 4 }} />
                                {data.model_info.created_on ? formatDate(data.model_info.created_on) : '未知'}
                            </span>
                        </Descriptions.Item>
                    </Descriptions>
                    {data.model_info.description && (
                        <div style={{ marginTop: 12, padding: 12, background: '#f5f5f5', borderRadius: 6 }}>
                            <strong>描述:</strong> {data.model_info.description}
                        </div>
                    )}
                </Card>
            )}

            {/* 统计信息 */}
            {data.statistics && (
                <Card 
                    title={
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <BarChartOutlined style={{ marginRight: 8, color: '#52c41a' }} />
                            版本统计
                        </div>
                    }
                    size="small" 
                    style={{ marginBottom: 16 }}
                >
                    <div style={{ display: 'flex', justifyContent: 'space-around', textAlign: 'center' }}>
                        <div>
                            <div style={{ fontSize: 24, fontWeight: 'bold', color: '#1890ff' }}>
                                {data.statistics.total_versions}
                            </div>
                            <div style={{ fontSize: 12, color: '#666' }}>总版本数</div>
                        </div>
                        <div>
                            <div style={{ fontSize: 16, fontWeight: 'bold', color: '#52c41a' }}>
                                {data.statistics.version_types?.length || 0}
                            </div>
                            <div style={{ fontSize: 12, color: '#666' }}>版本类型</div>
                            {data.statistics.version_types && data.statistics.version_types.length > 0 && (
                                <div style={{ marginTop: 4 }}>
                                    {data.statistics.version_types.map(type => (
                                        <Tag key={type} color={getVersionTypeColor(type)}>
                                            {type}
                                        </Tag>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                </Card>
            )}

            {/* 版本时间线 */}
            <Card 
                title={
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                        <span>
                            <ClockCircleOutlined style={{ marginRight: 8, color: '#722ed1' }} />
                            版本演进时间线
                        </span>
                        {data.timeline && data.timeline.length > 5 && (
                            <Button 
                                size="small" 
                                type="link"
                                icon={showAllVersions ? <UpOutlined /> : <DownOutlined />}
                                onClick={() => setShowAllVersions(!showAllVersions)}
                            >
                                {showAllVersions ? '收起' : `显示全部 (${data.timeline.length})`}
                            </Button>
                        )}
                    </div>
                }
                size="small"
            >
                <Timeline mode="left">
                    {visibleVersions?.map((version, index) => (
                        <Timeline.Item
                            key={version.id}
                            dot={getVersionTypeIcon(version.type, !!version.is_current)}
                            color={getVersionTypeColor(version.type)}
                        >
                            <Card 
                                size="small"
                                style={{ 
                                    marginBottom: 8,
                                    border: version.is_current ? '2px solid #52c41a' : '1px solid #d9d9d9',
                                    boxShadow: version.is_current ? '0 2px 8px rgba(82, 196, 26, 0.3)' : 'none'
                                }}
                                title={
                                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                        <div style={{ display: 'flex', alignItems: 'center' }}>
                                            <Tag color={getVersionTypeColor(version.type)}>
                                                {version.version}
                                            </Tag>
                                            {version.is_current && (
                                                <Tag color="success">当前版本</Tag>
                                            )}
                                            <span style={{ fontSize: 12, color: '#666', marginLeft: 8 }}>
                                                {formatDate(version.date)}
                                            </span>
                                        </div>
                                        {version.changelog && (
                                            <Button 
                                                size="small" 
                                                type="link"
                                                icon={expandedItems.has(version.id) ? <UpOutlined /> : <DownOutlined />}
                                                onClick={() => toggleExpanded(version.id)}
                                            >
                                                详情
                                            </Button>
                                        )}
                                    </div>
                                }
                            >
                                <div style={{ marginBottom: 8 }}>
                                    <strong>版本类型:</strong> 
                                    <Tag color={getVersionTypeColor(version.type)} style={{ marginLeft: 8 }}>
                                        {version.type}
                                    </Tag>
                                </div>

                                {version.creator && (
                                    <div style={{ marginBottom: 8 }}>
                                        <strong>创建者:</strong> 
                                        <span style={{ marginLeft: 8 }}>
                                            <UserOutlined style={{ marginRight: 4 }} />
                                            {version.creator}
                                        </span>
                                    </div>
                                )}

                                {version.framework && (
                                    <div style={{ marginBottom: 8 }}>
                                        <strong>框架:</strong>
                                        <Tag color="blue" style={{ marginLeft: 8 }}>
                                            {version.framework}
                                        </Tag>
                                    </div>
                                )}

                                {version.changelog && (
                                    <div style={{ marginBottom: 8 }}>
                                        <strong>变更说明:</strong>
                                        <div style={{ 
                                            marginTop: 8, 
                                            padding: 8, 
                                            background: '#f5f5f5', 
                                            borderRadius: 4,
                                            maxHeight: expandedItems.has(version.id) ? 'none' : '60px',
                                            overflow: 'hidden',
                                            transition: 'max-height 0.3s ease'
                                        }}>
                                            {version.changelog}
                                        </div>
                                    </div>
                                )}

                                {version.metrics && (
                                    <div style={{ marginBottom: 8 }}>
                                        <strong>指标信息:</strong>
                                        <div style={{ marginTop: 8, fontSize: 12, color: '#666' }}>
                                            {version.metrics}
                                        </div>
                                    </div>
                                )}

                                {version.performance && expandedItems.has(version.id) && (
                                    <div>
                                        <strong>性能指标:</strong>
                                        {renderPerformanceMetrics(version.performance)}
                                    </div>
                                )}
                            </Card>
                        </Timeline.Item>
                    ))}
                </Timeline>
            </Card>
        </div>
    );
};

export default ModelVersionTimeline;
